package com.lcu.wl.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcu.wl.annotation.Log;
import com.lcu.wl.common.exception.SYSException;
import com.lcu.wl.common.utils.Constant;
import com.lcu.wl.common.utils.SYSDATA;
import com.lcu.wl.modules.sys.entity.Menu;
import com.lcu.wl.modules.sys.service.IMenuService;
import com.lcu.wl.modules.sys.service.IShiroService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author wanglei
 * @since 2021-01-15
 */
@RestController
@RequestMapping("/sys/menu")
public class MenuController extends AbstractController{
    @Autowired
    private IMenuService iMenuService;
    @Autowired
    private IShiroService iShiroService;
    /**
     * 导航菜单
     */
    @GetMapping("/nav")
    public SYSDATA getNav(){
        List<Menu> menuList = iMenuService.getUserMenuList(getUserId());
        Set<String> permissions = iShiroService.getUserPermissions(getUserId());
        return SYSDATA.ok().put("menuList",menuList).put("permissions",permissions);
    }
    /**
     * 菜单树
     */
    @GetMapping("/tree")
    public SYSDATA getMenuTree(@RequestParam Long pid){
        List<Menu> menuTree = iMenuService.getMenuTree(pid);
        return SYSDATA.ok().put("menuTree",menuTree);
    }
    /**
     *根据菜单ID返回所有子节点ID，包含自身ID
     */
    @GetMapping("/child")
    public SYSDATA child(@RequestParam Long id){
        Set<Menu> menuSet = new HashSet<>();
        //懒加载查询子节点
        List<Menu> menuList = iMenuService.getMenuTree(id);
        menuSet.add(iMenuService.getById(id));
        if (menuList != null){
            menuSet = iMenuService.getChildMenus(menuList, menuSet);
        }
        Set<Long> ids = menuSet.stream().map(Menu::getMenuId).collect(Collectors.toSet());
        return SYSDATA.ok().put("childIds",ids);
    }

    /**
     * 所有菜单列表
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询菜单")
    @RequiresPermissions("sys:menu:list")
    public List<Menu> list(@RequestParam Map<String,Object> params){
        String menuname = (String)params.get("menuname");
        List<Menu> menuList = iMenuService.list(new QueryWrapper<Menu>()
                .like(StringUtils.isNotBlank(menuname),"name", menuname));
        return menuList;
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @GetMapping("/select")
    @RequiresPermissions("sys:menu:select")
    public SYSDATA select(){
        //查询列表数据
        List<Menu> menuList = iMenuService.queryNotButtonList();

        //添加顶级菜单
        Menu root = new Menu();
        root.setMenuId(0L);
        root.setName("顶级菜单");
        root.setParentId(-1L);
        //TODO 下级菜单数组固定，需要调整
        root.setSubCount(3);
        root.setLeaf(false);
        menuList.add(root);

        return SYSDATA.ok().put("menuList", menuList);
    }
    /**
     * 保存
     * @return
     */
    @Log("新增菜单信息")
    @ApiOperation("新增菜单")
    @PostMapping("/save")
    @RequiresPermissions("sys:menu:save")
    public SYSDATA save(@RequestBody Menu menu){
        verifyForm(menu);
        iMenuService.create(menu);
        return SYSDATA.ok();
    }

    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    @ApiOperation("根据ID获取菜单信息")
    @RequiresPermissions("sys:menu:info")
    public SYSDATA info(@PathVariable("menuId") Long menuId){
        Menu menu = iMenuService.getById(menuId);
        return SYSDATA.ok().put("menu", menu);
    }

    /**
     * 修改
     */
    @Log("修改菜单信息")
    @ApiOperation("修改菜单")
    @PostMapping("/update")
    @RequiresPermissions("sys:menu:update")
    public SYSDATA update(@RequestBody Menu menu){
        //数据校验
        verifyForm(menu);

        iMenuService.update(menu);

        return SYSDATA.ok();
    }

    /**
     * 删除
     */
    @Log("删除菜单信息")
    @ApiOperation("删除菜单")
    @PostMapping("/delete/{menuId}")
    @RequiresPermissions("sys:menu:delete")
    public SYSDATA delete(@PathVariable("menuId") Long menuId){
        if(menuId <= 19){
            return SYSDATA.error("系统菜单，不能删除");
        }

        //判断是否有子菜单或按钮
        List<Menu> menuList = iMenuService.getListParentId(menuId);
        if(menuList.size() > 0){
            return SYSDATA.error("请先删除子菜单或按钮");
        }

        iMenuService.delete(menuId);

        return SYSDATA.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(Menu menu){
        if(StringUtils.isBlank(menu.getName())){
            throw new SYSException("菜单名称不能为空");
        }

        if(menu.getParentId() == null){
            throw new SYSException("上级菜单不能为空");
        }

        //菜单
        if(menu.getType() == Constant.MenuType.MENU.getValue()){
            if(StringUtils.isBlank(menu.getUrl())){
                throw new SYSException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if(menu.getParentId() != 0){
            Menu parentMenu = iMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if(menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()){
            if(parentType != Constant.MenuType.CATALOG.getValue()){
                throw new SYSException("上级菜单只能为目录类型");
            }
            return ;
        }

        //按钮
        if(menu.getType() == Constant.MenuType.BUTTON.getValue()){
            if(parentType != Constant.MenuType.MENU.getValue()){
                throw new SYSException("上级菜单只能为菜单类型");
            }
            return ;
        }
    }

}
